'use client';

import React, { useState } from 'react';
import { usePost } from '@/hooks/useRequest';
import { LoginSchema, type LoginRequest } from '@/types/models';
// import { useAuth } from '@/hooks/useAuth';
import { z } from 'zod';
import { useRouter } from 'next/navigation';

export function LoginForm() {
  const [formData, setFormData] = useState<LoginRequest>({
    email: '',
    password: '',
  });

  const router = useRouter();

  const { mutate: login, isLoading, error } = usePost<{ token: string }, LoginRequest>(
    '/auth/login',
    {
      onSuccess: (data) => {
        localStorage.setItem('token', data.token);
        // 处理登录成功
      },
      onError: (error) => {
        console.error('登录失败:', error.message);
      },
    }
  );

  const handleSubmit = async (e: React.FormEvent) => {
    console.log(111);
    e.preventDefault();
    router.push('settings');
    try {
      // 验证表单数据
      const validatedData = LoginSchema.parse(formData);
      login(validatedData);
    } catch (err) {
      if (err instanceof z.ZodError) {
        console.error('表单验证错误:', err.errors);
      }
    }
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      {error && (
        <div className="bg-red-100 p-2 rounded" onClick={() => {}}>
          {error.message}
        </div>
      )}
      <div>
        <input
          type="email"
          value={formData.email}
          onChange={(e) => setFormData({ ...formData, email: e.target.value })}
          placeholder="邮箱"
          className="w-full p-2 border rounded"
        />
      </div>
      <div>
        <input
          type="password"
          value={formData.password}
          onChange={(e) => setFormData({ ...formData, password: e.target.value })}
          placeholder="密码"
          className="w-full p-2 border rounded"
        />
      </div>
      <button
        type="submit"
        disabled={isLoading}
        className="w-full p-2 bg-blue-500 text-white rounded disabled:bg-blue-300"
      >
        {isLoading ? '登录中...' : '登录'}
      </button>
    </form>
  );
} 